package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author xiaoping
 * @create 2020/7/1 19:06
 * @since 1.0.0
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    /**
     * 添加商品到购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //添加新商品到购物车
        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res)){
            CartItem cartItem = new CartItem();
            //购物车无此商品
            //异步编排设置sku信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1,远程查询当前需要添加的商品信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuInfo.getSkuId());
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);
            //3，远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);
            //等待线程执行完成
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();

            //保存商品信息到redis
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
            return  cartItem;
        }else {
            //购物车有此商品，修改数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            //更新缓存
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 查询购物车信息
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(str, CartItem.class);
    }

    /**
     * 获取整个购物车
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //获取共享用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //判断是否登录
        if (userInfoTo.getUserId() != null){
            //登录的购物车key
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //临时购物车数据
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if(tempCartItems != null ){
                //临时购物车有数据，需要合并
                for (CartItem item : tempCartItems) {
                    //添加购物车
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清除临时购物车数据
                System.out.println("临时购物车:" + tempCartKey);
                clearCart(tempCartKey);
            }
            //获取整合后的购物车数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else{
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     *  获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //得到共享用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        //判断是否登录
        if (userInfoTo.getUserId() != null){
            //gulimall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            //没登陆走临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        //绑定缓存key
        return redisTemplate.boundHashOps(cartKey);
    }


    /**
     * 获取购物车信息
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if(values != null && values.size() > 0){
            return values.stream().map((obj) -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 修改选中项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    /**
     * 改变商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    /**
     * 删除购物车商品
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取当前会员选中的购物项
     * @return
     */
    @Override
    public List<CartItem> getUserCartItem() {
        //获取共享用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo != null){
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //获取购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            //获取选中的购物项
            if (cartItems != null) {
                return cartItems.stream().filter(CartItem::getCheck)
                        .peek(item -> {
                            /*更新为最新价格*/
                            R r = productFeignService.getPrice(item.getSkuId());
                            String data = (String) r.get("data");
                            item.setPrice(new BigDecimal(data) );
                        }).collect(Collectors.toList());
            }
        }
        return null;
    }

}
